;(function($) {
	$.fn.linkageselector = function(name, url, keep, endless) {
		var $selector = $(this);
		var layer = parseInt($selector.attr('layer'));
		var group = $selector.attr('group');
		var $next = $('select[group="'+group+'"][layer="'+(layer+1)+'"]');
		var $prev = $('select[group="'+group+'"][layer="'+(layer-1)+'"]');
		var $hidden = $(':hidden[name="'+$selector.attr('name')+'"]');
		var url = url;
		var name = name;
		var keep = keep;
		var endless = endless;
		
		$selector.data('linkageselector', {
			keep: keep,
			endless: endless
		});
		
		$selector.change(function() {
			
			nextLayer = layer+1;
			if(!this.value) {
				$hidden.val($prev.val());
			} else {
				$hidden.val(this.value);
			}
			$.get(url, 
				{name: name, layer: nextLayer, value: $selector.val()}, 
				function(data) {
					
					$('select[group="'+group+'"]').each(function(i, e) {
						$e = $(e);
						eLayer = $e.attr('layer');
						keep = $e.data('linkageselector').keep;
						endless = $e.data('linkageselector').endless;
						if(parseInt(eLayer) > layer) {
							$e.children().not(':first').remove();
							if(!keep) $e.hide();
							if(endless) $e.remove();
						}
					});
					
					if(endless && data.itemCount > 0) {
						$next.remove();
						$next = $selector.clone();
						$next.attr('layer', nextLayer);
						$next.attr('id', $next.attr('id')+'_'+nextLayer);
						$next.css('display', 'none');
						$next.insertAfter($selector);
					}
					if(data.itemCount > 0)
						$next.html(data.html).show();
					
					$next.linkageselector(name, url, keep, endless);
				},
				'json'
			);
			
		});
		
		
	}
})(jQuery);